package jmine.tec.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jmine.tec.utils.io.IOUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {

    public static volatile byte[] theFile;
    
    public static volatile String parameter, expectedParameterName;

    public static volatile Exception exception;
    
    @SuppressWarnings("unchecked")
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)) { 
            final DiskFileItemFactory factory = new DiskFileItemFactory();
            final ServletFileUpload upload2 = new ServletFileUpload(factory);
            try {
                List<FileItem> parseRequest = upload2.parseRequest(req);
                for (FileItem fileItem : parseRequest) {
                    if(fileItem.isFormField()) {
                        if(fileItem.getFieldName().equals(expectedParameterName)) {
                            parameter = fileItem.getString();
                        } else {
                            resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, "expected: " + expectedParameterName + " but was: " + fileItem.getFieldName());
                        }
                    } else {
                        theFile = IOUtils.readFully(fileItem.getInputStream());
                    }
                }
            } catch (FileUploadException e) {
                exception = e;
            }
        }
    }

}
